

package top.continew.admin.question.user.service.question.entity;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.Data;
import top.continew.admin.question.model.question.Question;
import top.continew.admin.question.model.question.QuestionSelect;
import top.continew.admin.question.user.service.question.enums.ProblemStateEnum;
import top.continew.admin.question.user.service.question.enums.QuestionTypeEnum;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

@Data
public class MultipleChoiceQuestion extends AbstractQuestion implements ISelectQuestion {

    private List<QuestionSelect> select;

    @Override
    public void init(Question question) {
        super.init(question);
        select = new QuestionSelect().selectList(Wrappers.lambdaQuery(QuestionSelect.class)
            .eq(QuestionSelect::getQuestionId, question.getId()));
    }

    @Override
    public CorrectResult correct(String userAnswer) {
        CorrectResult correctResult = new CorrectResult();
        correctResult.setCorrectAnswer(answer);
        correctResult.setUserAnswer(userAnswer);
        correctResult.setProblemState(ProblemStateEnum.UNCHECK.getCode());

        if (userAnswer == null || userAnswer.trim().isEmpty()) {
            return correctResult;
        }

        try {
            String[] userAnswerArray = userAnswer.split(",");
            List<String> answerList = JSON.parseArray(answer, String.class);

            // 检查答案数量是否匹配
            if (userAnswerArray.length != answerList.size()) {
                correctResult.setProblemState(ProblemStateEnum.WRONG.getCode());
                return correctResult;
            }

            // 对两个答案列表进行排序以确保一致的比较
            Arrays.sort(userAnswerArray);
            Collections.sort(answerList);

            // 逐一比较答案
            for (int i = 0; i < userAnswerArray.length; i++) {
                if (!userAnswerArray[i].equals(answerList.get(i))) {
                    correctResult.setProblemState(ProblemStateEnum.WRONG.getCode());
                    return correctResult;
                }
            }

            correctResult.setProblemState(ProblemStateEnum.RIGHT.getCode());
        } catch (Exception e) {
            correctResult.setProblemState(ProblemStateEnum.WRONG.getCode());
        }

        return correctResult;
    }

    @Override
    public Integer getType() {
        return QuestionTypeEnum.MULTIPLE_CHOICE_QUESTIONS.getCode();
    }

    @Override
    public String getTypeName() {
        return QuestionTypeEnum.MULTIPLE_CHOICE_QUESTIONS.getName();
    }
}